package org.apache.ibatis.type;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Object.class)
public class EntityTypeHandler extends BaseTypeHandler<Object> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object object, JdbcType jdbcType) throws SQLException {
    if(object == null){
        preparedStatement.setString(i, null);
    }
    else{

        JSONObject json = (JSONObject)JSON.toJSON(object);
        json.put("@class", object.getClass().getTypeName());
        preparedStatement.setString(i, json.toJSONString());
    }
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        if(value == null){
          return null;
        }
        JSONObject json = JSON.parseObject(value);
        String classPath = json.getString("@class");
        json.remove("@class");
        try{
          Class<?> clazz = Class.forName(classPath);
          return JSONObject.parseObject(json.toString(), clazz);

        }
        catch (ClassNotFoundException ex){
          logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    @Override
    public JSON getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public JSON getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}